import React from 'react';
import HeaderTab from '@/components/HeaderTab';
import { connect } from 'dva';
import router from 'umi/router';
import {Card, Button, Form,Table, Row, Col, DatePicker,Input,Spin,Select, Tooltip} from 'antd';
import styles from './list.less';
import ImportExpress from './importExpress';

const { RangePicker } = DatePicker;
const { Option } = Select;
const FormItem = Form.Item;
@Form.create()
class Batchdelivery extends React.Component {
    constructor() {
        super();
        this.state={
            tableLoading: false,
            btnLoading: false,
            loading: true,
            dataSource: [],
            paginationProps: {
                showSizeChanger: true,
                showQuickJumper: false,
                showTotal: total => `共 ${total} 条记录`,
                pageSize: 10,
                total: 0,
                pageIndex: 1,
              },
            tabs: [
                {
                  title: '发货管理',
                  key: `/${window.storeId}/order/delivery`,
                },
                {
                  title: '批量发货',
                  key: `/${window.storeId}/order/delivery/batch`,
                },      
              ],
        }
    }

// 头部状态切换
   onTabChange = id => {
    this.setState(
      {
        activeId: id,
      },
      () => {
        router.replace({
          pathname: `${id}`,
        });
      }
    );
  };

  componentWillMount() {
      this.requestImportLogList();
      window.Isoption = false;
  }

  componentDidMount() {
    window.Isoption = true;
  }

  requestImportLogList =params=> {
    const { dispatch} = this.props;
    const { paginationProps: { pageIndex, pageSize }} = this.state;
    dispatch({
        type: 'deliverManage/ImportLog',
        payload: {
            PageIndex: pageIndex, //页码
            PageSize: pageSize, //页数
            MinDate: params && params.MinDate? params.MinDate: null,
            MaxDate: params && params.MaxDate? params.MaxDate: null,
            OperMan: params && params.OperMan? params.OperMan: '',
            State: params && params.State? params.State: 0,
        },
        callback: {
            success: res => {
                if(res.Code ===0) {
                    this.setState({
                        paginationProps: {
                            ...this.state.paginationProps,
                            total: res.Data.Total
                        },
                        dataSource: res.Data&&res.Data.DataList?res.Data.DataList:[],
                        loading: false,
                        btnLoading: false,
                        tableLoading: false,
                    })
                }
            },
            error: res => {
                console.log(res);
            }
        }
    })
  }

    // 重置
    handleFormReset =() => {
        const { form } = this.props;
        form.resetFields();
      }

  handleSearch =(e) => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, values) => {
        if(err) return;
        const datas = {
            ...values,
            MinDate:values.Date && values.Date[0]?moment(values.Date[0]).format('YYYY-MM-DD'):'',
            MaxDate:values.Date && values.Date[1]?moment(values.Date[1]).format('YYYY-MM-DD'):'',         
        };
        this.setState({
            formValues: datas,
            btnLoading: true,
            tableLoading: true,
        })
        this.requestImportLogList({...datas});
    })
  }

  refech =()=> {
      const {formValues} = this.state;
      this.requestImportLogList({...formValues});
  }

  clickExpress =() => {
      const width =640;
      const title="批量发货"
      this.importExpress.show({width, title}, this.refech)
  }

  onTableChange =(pagination)=> {
    let {paginationProps, formValues} = this.state;
    let data = {
        ...paginationProps,
        pageIndex: pagination.current,
        pageSize: pagination.pageSize,
    };
    this.setState({
        paginationProps: data,
        formValues,
        tableLoading: true,
    }, ()=> {
        this.requestImportLogList({...formValues})
    })
  }

  
  renderForm() {
    const {form: { getFieldDecorator }} = this.props;
    const {btnLoading} = this.state;

    return (
        <Form layout="inline" onSubmit={this.handleSearch}>
            <Row>
                <Col span={8}>
                    <FormItem label="发送时间">
                    {getFieldDecorator('Date')(
                        <RangePicker style={{ width: '100%' }} placeholder={['开始日期', '结束日期']} />
                    )}
                    </FormItem>
                </Col>
                <Col span={8}>
                    <FormItem label="状态">
                        {getFieldDecorator('State', {initialValue: 0})(
                            <Select placeholder="请选择" style={{ width: '100%' }}>
                                <Option value={0}>全部</Option>
                                <Option value={1}>处理中</Option>
                                <Option value={2}>已完成</Option>
                            </Select>
                        )}
                    </FormItem>
                </Col>
                <Col span={8}>
                    <FormItem label="操作人">
                    {getFieldDecorator('OperMan')(
                        <Input style={{ width: '100%' }}/>
                    )}
                    </FormItem>
                </Col>      
            </Row>
            <div style={{ overflow: 'hidden' }}>
                <div className="screenNavButton">
                    <Button type="primary" htmlType="submit" loading={btnLoading}>
                        筛选
                    </Button>
                    <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                        重置
                    </Button>
                </div>
            </div>
        </Form>
    )
  }

    render() {
        const {tabs, dataSource, tableLoading, loading} = this.state;
        const columns =[
            {
                title: '记录编号',
                dataIndex: 'TaskNumber',
                key: 'TaskNumber',
            },
            {
                title: '操作时间',
                dataIndex: 'CreateTime',
                key: 'CreateTime',
            },
            {
                title: '操作人',
                dataIndex: 'Operator',
                key: 'Operator',
            },
            {
                title: '发货单数',
                align: 'right',
                render: (Text, data) => {
                    return (
                        <span>{data.ResultJson?JSON.parse(data.ResultJson).AllCount:'-'}</span>
                    )
                }
            },
            {
                title: '成功发货单数',
                align: 'right',
                render: (Text, data) => {
                    return (
                        <span>{data.ResultJson?JSON.parse(data.ResultJson).SucessCount:'-'}</span>
                    )
                }
            },
            {
                title: '状态',
                dataIndex: 'StateName',
                key: 'StateName',
            },
            {
                title: '操作',
                align: 'right',
                render: (Text, data) => {
                    if(data.State===0 || data.State===1) {
                        return (
                            <span>报表生成中</span>
                        )
                    }
                    if(data.ExportFileUrl){
                        return (
                            <a href={data.ExportFileUrl} download style={{textDecoration:'none'}}>下载发货记录</a>
                        )
                    }
                    if (data.State===-1){
                        return (
                            <Tooltip title={data.Remark} getPopupContainer={() => document.querySelector(`.batchdelivery`)}>
                                <span >详情</span>
                            </Tooltip>                           
                        )
                    }   
                }
            },
        ];
        return (
            <div className="batchdelivery">
                {/* <HeaderTab
                    _this={this}
                    type="slider"
                    activeId={this.state.activeId}
                    onChange={this.onTabChange}
                    tabs={tabs}
                >
                </HeaderTab> */}

                <Spin spinning={loading}>
                    <Card bordered={false} style={{marginBottom: 16}}>
                        <div className={styles.header}>批量发货</div>
                        <p>批量发货目前仅支持快递订单，暂不支持自提订单和同城配送方式的订单。提高操作发货的成功率：</p>
                        <p>1. 按模板要求填写发货信息，注意运单号不要写成E+22科学计数法；</p>
                        <p>2. 下载【查看失败原因】，对症修改，成功率更高。</p>
                        <p style={{marginTop: 8}}><a>表格导入发货教程</a></p>
                    </Card>
                    <Card bordered={false} >
                        <Button type="primary" onClick={this.clickExpress}>批量发货</Button>
                        <div style={{
                                height:112,
                                background:'#fafafa',
                                marginBottom:16,
                                paddingTop:16,
                                paddingRight:16,
                                boxSizing:'border-box',
                                marginTop: 16
                            }}>
                            <div className="tableListForm">{this.renderForm()}</div>
                        </div>
                        <Spin spinning={tableLoading}>
                            <Table
                                columns={columns}
                                dataSource ={dataSource?dataSource:[]}
                                rowKey={record => record.Id}
                                onChange={this.onTableChange}
                                pagination={this.state.paginationProps}
                                onRow={(record) => {
                                    return {
                                    onMouseEnter: (event) => {},  // 鼠标移入行
                                    };
                                }}
                            />
                        </Spin>
                    </Card>
                </Spin>

                <ImportExpress
                    ref={e=> {
                        this.importExpress = e
                    }}
                />
            </div>
        )
    }
}

export default connect(({ deliverManage, global, loading }) => ({ 
    cdnUrl:global.oemInfo.cdnUrl,
  }))(Batchdelivery);;